package finance

import org.joda.time.DateTimeConstants

class HistoricalQueryService {

    static transactional = true

    def queryVals(symbol,fieldName) {
		def instrument = Instrument.findBySymbol(symbol)
		def field = Field.findByName(fieldName)
		def fieldVals = FieldValue.findAllByInstrumentAndField(instrument, field)
        fieldVals = fieldVals.sort { a, b -> a.added <=> b.added }
		def data = []
		
		fieldVals.each {  data << Double.valueOf( it.val )}
        
		return data
    }

    def queryWeeklyVals(symbol,fieldName) {
		def instrument = Instrument.findBySymbol(symbol)
		def field = Field.findByName(fieldName)
		def fieldVals = FieldValue.findAllByInstrumentAndField(instrument, field)
      fieldVals = fieldVals.findAll { it.added.getDayOfWeek() == DateTimeConstants.FRIDAY }
      fieldVals = fieldVals.sort { a, b -> a.added <=> b.added }
		def data = []
		
		fieldVals.each {  data << Double.valueOf( it.val )}
        
		return data
    }
	
    def queryPairVals(symbol, symbol2, fieldName) {
		def instrument = Instrument.findBySymbol(symbol)
		def instrument2 = Instrument.findBySymbol(symbol2)
		def field = Field.findByName(fieldName)
		def fieldVals = FieldValue.findAllByInstrumentAndField(instrument, field)
		def fieldVals2 = FieldValue.findAllByInstrumentAndField(instrument2, field)
		
		def data = []
		
		for(int i = 0; i < fieldVals.size() && i < fieldVals2.size(); i++) {
			def sameDateVal = fieldVals2.each { 
				if(fieldVals[i].added == it.added) {
					return it.val
				}
			}
		
			if(sameDateVal == null) continue	
			
			data << Double.valueOf(fieldVals[i].val) - Double.valueOf(sameDateVal[0].val)
		}
		
		return data
    }
    
    def pairedValuesMap(symbol, symbol2, fieldName) {
		def instrument = Instrument.findBySymbol(symbol)
		def instrument2 = Instrument.findBySymbol(symbol2)
		def field = Field.findByName(fieldName)
		def fieldVals = FieldValue.findAllByInstrumentAndField(instrument, field)
		def fieldVals2 = FieldValue.findAllByInstrumentAndField(instrument2, field)
		
		def map = [:]
	    def data1 = []	
	    def data2 = []	
        
		for(int i = 0; i < fieldVals.size() && i < fieldVals2.size(); i++) {
			def sameDateVal = fieldVals2.each { 
				if(fieldVals[i].added == it.added) {
					return it.val
				}
			}
		
			if(sameDateVal == null) continue	
			
			data1 << Double.valueOf(fieldVals[i].val) 
            data2 << Double.valueOf(fieldVals2[i].val)
		}
        
        map["data1"] = data1
        map["data2"] = data2
		
		return map
    }
}
